package cn.bob.service.impl;

import cn.bob.domain.MovieTicket;
import cn.bob.domain.User;
import cn.bob.dto.BuyNumDto;
import cn.bob.exception.GlobalException;
import cn.bob.feign.MovieServer;
import cn.bob.mapper.UserMapper;
import cn.bob.result.JsonResult;
import cn.bob.service.IUserMovieService;
import cn.bob.service.IUserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bob
 * @since 2022-11-23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    public MovieServer movieServer;

    @Override
    public JsonResult movie() {
        return movieServer.list();
    }

    @Override
    public JsonResult userBuy(BuyNumDto buyNumDto) {
        JsonResult buy = movieServer.buy(buyNumDto);
        if (!buy.getMessage().equals("成功")){
            return buy;
        }
        //修改user的金额
        //查询到用户
        User user = selectById(buyNumDto.getUserId());
        if (user==null){
            throw new GlobalException("用户不存在！！");
        }

        JsonResult jsonResult = movieServer.get(buyNumDto.getId());
        if (jsonResult==null){
            throw new GlobalException("电影不存在！！");
        }

        MovieTicket movieTicket = JSONObject.parseObject(JSON.toJSONString(jsonResult.getData()), MovieTicket.class);
        if (movieTicket==null){
            return jsonResult;
        }
        //计算金额
        BigDecimal price = movieTicket.getPrice().multiply(new BigDecimal(buyNumDto.getNum()));
        user.setBalance(user.getBalance().subtract(price));
        updateById(user);
        return JsonResult.success("购买成功："+buyNumDto.getNum());
    }

    @Override
    public JsonResult seeMovie(BuyNumDto buyNumDto) {
        return movieServer.seeMovie(buyNumDto);
    }

    @Override
    public boolean insert(User entity) {
        boolean insert = super.insert(entity);
        //获取随机电影票一张
        movieServer.randomMovie(entity.getId());
        return insert;
    }
}
